import pymysql


class DBUtils:

    def __init__(self, host="localhost", port=3306, user="root", password=None, database=None, charset="utf8"):
        self.__db = pymysql.connect(host=host, port=port, user=user, password=password,
                                    database=database, charset=charset)

    def __del__(self):
        self.__db.close()

    def update(self, sql, params=None):
        try:
            with self.__db.cursor() as cursor:
                cursor.execute(sql, params)
                self.__db.commit()
                print("数据库更新成功！")
        except Exception as e:
            print("数据库更新失败！原因：", e)

    def select(self, sql, params=None, size=None):
        try:
            with self.__db.cursor() as cursor:
                cursor.execute(sql, params)
                if size is None:
                    data = cursor.fetchall()
                else:
                    data = cursor.fetchmany(size)
                print("数据库查询成功！")
                return data
        except Exception as e:
            print("数据库查询失败！原因；", e)


if __name__ == '__main__':
    db = DBUtils(password="123456", database="study")

    sql = "UPDATE students SET `name` = %s WHERE `id` = %s"
    db.update(sql, ("哇咔咔", 1))

    # sql = "SELECT * FROM `students` WHERE `gender` = %s"
    # res = db.select(sql, ("男",), 5)
    # print(res)

    del db
